package com.example.pdfdemo.pdf;


import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author fanhailong
 */
@Slf4j
@RestController
@RequestMapping("/pdf")
public class PdfController {

    @RequestMapping("/export")
    public void exportPdf(HttpServletResponse response) throws Exception {
        ByteArrayOutputStream baos = null;
        OutputStream out = null;
        try {
            TemplateBO templateBO = TemplateBO.builder()
                    .productName("含笑半步癫")
                    .productFeatures("居家旅行必备")
                    .imageUrl1("/Users/fanhailong/Pictures/素材/0.png")
                    .imageUrl2("/Users/fanhailong/Pictures/素材/1.jpg")
                    .build();
            baos = PdfTemplateUtil.createPDF(templateBO);
            response.setContentType("application/x-download");
            String fileName = URLEncoder.encode("product.pdf", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            baos.writeTo(out);
        } catch (Exception e) {
            log.error("导出失败" + e);
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

